<?php

namespace App\Http\Controllers\Wechat;

use App\Models\UserInfo;
use App\Models\UserLibraryInfo;
use App\Validate\UserInfoValidate;
use App\Http\Controllers\Controller;
use App\Http\Controllers\LibApi\GshqLibController;
use App\Http\Controllers\LibApi\YzRecomController;
use App\Models\AccessNumUser;
use App\Models\ActivityApply;
use App\Models\GoodsOrder;
use App\Models\ResourceUserReadBookDay;
use App\Models\ScoreInfo;
use App\Models\ScoreLog;
use App\Models\ScoreReset;
use App\Models\SignScore;
use App\Models\SystemInfo;
use App\Models\UserAppletInfo;
use App\Models\UserWechatInfo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 用户基本信息
 */
class UserInfoController extends Controller
{
    public $model = null;
    public $libraryInfoModel = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new UserInfo();
        $this->libraryInfoModel = new UserLibraryInfo();
        $this->validate = new UserInfoValidate();
    }



    /**
     * 获取用户积分明细
     * @param token ：用户 token
     * @param page 页数
     * @param limit 限制条数
     */
    public function scoreList()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $user_id = $this->request->user_info['id'];
        // $account_id = $this->request->user_info['account_id'];
        $res = ScoreLog::select('id', 'score', 'type', 'type_id', 'intro', 'create_time')->where('user_id', $user_id)->orderByDesc('create_time')->paginate($limit)->toArray();

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        $data = $this->disPageData($res);
        $data['score'] = UserInfo::where('id', $user_id)->value('score');

        foreach ($data['data'] as $key => $val) {
            if ($val['type_id'] === 0 || $val['type_id'] === '0') {
                $data['data'][$key]['type_icon'] = '兑';
            } elseif (empty($val['type_id'])) {
                $data['data'][$key]['type_icon'] = '其';
            } else {
                $data['data'][$key]['type_icon'] = ScoreInfo::where('id', $val['type_id'])->value('type_icon');
                $data['data'][$key]['type_icon'] =  $data['data'][$key]['type_icon'] ?  $data['data'][$key]['type_icon'] : '其';
            }
        }
        return $this->returnApi(200, "获取成功", true, $data);
    }



    /**
     * 个人中心首页
     * @param token ：用户 token 可选   有token先传token
     //* @param open_id ：用户 open_id   二选一
     */
    public function index()
    {
        $user_id = $this->request->user_info['id'];
        $default_head_img = $this->getImgAddrUrl() . 'default/default_head_img.png';

        $data['head_img'] = $default_head_img;
        $data['nickname'] = '';
        $data['system_info_number'] = 0;
        $data['is_unread_info'] = false;
        $data['score'] = 0;
        $data['qr_url'] = ''; //推广二维码
        $data['account_qr_url'] = ''; //读者证二维码
        $data['qr_code'] = '';
        $data['is_sign'] = false;
        $data['invite_user'] = config('other.invite_user'); //是否显示邀请二维码按钮

        //读者证信息
        $data['account'] = '';
        $data['username'] = '';

        //   if ($user_id) {
        $user_info = UserInfo::where('id', $user_id)->first();
        // $data['score'] = $user_info['score'];
        $data['qr_url'] = $user_info['qr_url']; //推广二维码
        $data['wechat_qr_url'] = $user_info['wechat_qr_url']; //推广二维码 微信公众号
        $data['qr_code'] = $user_info['qr_code'];
        $data['serial_number'] = $user_info['serial_number']; //编号

        //直接获取用户表数据
        $data['head_img'] = stripos($user_info['head_img'], 'http') !== false ? $user_info['head_img'] : config('img_addr') . $user_info['head_img'];
        $data['nickname'] = $user_info['nickname'];

        // if (!empty($user_info['wechat_id'])) {
        //     $wechat_info = UserWechatInfo::where('id', $user_info['wechat_id'])->first();

        //     $data['head_img'] = stripos($wechat_info['head_img'], 'http') !== false ? $wechat_info['head_img'] : config('img_addr') . $wechat_info['head_img'];
        //     $data['nickname'] = $wechat_info['nickname'];
        // }
        if (!empty($user_info['account_id'])) {
            $library_info = UserLibraryInfo::where('id', $user_info['account_id'])->first();
            $data['account_qr_url'] = $library_info['qr_url'] ?? null; //读者证二维码
            $data['account'] = $library_info['account'] ?? null;
            $data['username'] = $library_info['username'] ?? null;
            $data['score'] = $library_info['score'] ?? null;
            $data['end_time'] = $library_info['end_time'] ?? null;
        }

        // if (!empty($user_info['applet_id'])) {
        //     $wechat_info = UserAppletInfo::where('id', $user_info['applet_id'])->first();
        //     $data['head_img'] = stripos($wechat_info['head_img'], 'http') !== false ? $wechat_info['head_img'] : config('img_addr') . $wechat_info['head_img'];
        //     $data['nickname'] = $wechat_info['nickname'];
        // }
        //获取系统消息个数
        $data['system_info_number'] = SystemInfo::where('user_id', $user_id)->count();
        //是否有未读消息
        $data['is_unread_info'] = SystemInfo::where('user_id', $user_id)->where('is_look', 2)->count() ? true : false;

        //获取系统消息个数
        $is_sign = SignScore::where('user_id', $user_id)->where('date', date('Y-m-d'))->first();
        $data['is_sign'] = $is_sign ? true : false;

        //获取今日阅读，本周阅读，本年阅读，累计阅读时长，累计阅读天数
        $resourceUserReadBookDayModel = new ResourceUserReadBookDay();
        $data['read_duration_day'] = minute_to_hour($resourceUserReadBookDayModel->getUserReadDuration($user_id, null, null, 'day'));
        $data['read_duration_week'] = minute_to_hour($resourceUserReadBookDayModel->getUserReadDuration($user_id, null, null, 'week'));
        $data['read_duration_month'] = minute_to_hour($resourceUserReadBookDayModel->getUserReadDuration($user_id, null, null, 'month'));
        $data['read_duration_year'] = minute_to_hour($resourceUserReadBookDayModel->getUserReadDuration($user_id, null, null, 'year'));
        $data['read_duration_total'] = minute_to_hour($resourceUserReadBookDayModel->getUserReadDuration($user_id));

        $accessNumUserModel = new AccessNumUser();
        $data['access_day'] = $accessNumUserModel->getUserAccessDay($user_id);

        return $this->returnApi(200, "获取成功", true, $data);
    }
    /**
     * 获取用户阅读时长量
     * @param token 用户guid
     */
    public function getUserReadDuration()
    {
        $user_id = $this->request->user_info['id'];
        $data = [];
        $resourceUserReadBookDayModel = new ResourceUserReadBookDay();
        $data['read_duration_day'] = $resourceUserReadBookDayModel->getUserReadDuration($user_id, null, null, 'day');
        $data['read_duration_week'] = $resourceUserReadBookDayModel->getUserReadDuration($user_id, null, null, 'week');
        $data['read_duration_month'] = $resourceUserReadBookDayModel->getUserReadDuration($user_id, null, null, 'month');
        $data['read_duration_year'] = $resourceUserReadBookDayModel->getUserReadDuration($user_id, null, null, 'year');
        $data['read_duration_total'] = $resourceUserReadBookDayModel->getUserReadDuration($user_id);
        $data['user_rank'] = $resourceUserReadBookDayModel->getUserReadRank($user_id, null, null, 'week');

        $accessNumUserModel = new AccessNumUser();
        $data['access_day'] = $accessNumUserModel->getUserAccessDay($user_id);

        return $this->returnApi(200, "获取成功", true, $data);
    }


    /**
     * 修改头像 和 昵称
     * @param token 用户guid
     * @param nickname 用户昵称
     * @param head_img 用户头像
     */
    public function wechatInfoChange()
    {
        $user_id = $this->request->user_info['id'];
        $nickname = $this->request->nickname;
        $head_img = $this->request->head_img;
        if (empty($nickname) && empty($head_img)) {
            return $this->returnApi(202, "参数错误");
        }
        if (mb_strlen($nickname) > 10) {
            return $this->returnApi(202, "用户昵称不能超过10个字符");
        }

        $userInfo = new UserInfo();
        $res = $userInfo->userInfoChange($user_id, $nickname, $head_img);
        if ($res) {
            return $this->returnApi(200, "修改成功", true);
        }
        return $this->returnApi(202, "修改失败");
    }
    /**
     * 获取推广二维码 （暂时不对外使用）
     * @parma token 用户token
     */
    public function getExtensionQrCode()
    {
        $user_id = $this->request->user_info['id'];
        $user_info = UserInfo::where('id', $user_id)->first();
        $qr_code = $user_info['qr_code'];

        $appletObj = new AppletAuthController();
        $res = $appletObj->getAppletQrCode($qr_code);
        if ($res) {
            return $this->returnApi(200, "获取成功", true, $res);
        }
        return $this->returnApi(202, "获取失败");
    }

    /**
     * 获取邀请用户列表
     * @param token 用户guid
     * @param page int 页码
     * @param limit int 分页大小
     */
    public function getInviteUserList()
    {
        $user_id = $this->request->user_info['id'];
        $limit = $this->request->limit ? $this->request->limit : 10;
        $res = $this->model->getInviteUserLists($user_id, $limit);
        if ($res['data']) {
            foreach ($res['data'] as $key => $val) {
                $res['data'][$key]['create_time'] = date('Y-m-d', strtotime($val['create_time']));
            }
            $res = $this->disPageData($res);
            return $this->returnApi(200, "获取成功", true, $res);
        }
        return $this->returnApi(203, "暂无数据");
    }

    /**
     * 获取 YUE书馆 的读者信息
     * @user_id 用户id    必须要微信授权
     */
    public function getLibReaderInfo()
    {
        $user_id = $this->request->user_info['id'];
        $user_info = UserInfo::where('id', $user_id)->first();
        if (empty($user_info['applet_id'])) {
            return $this->returnApi(202, "信息获取失败");
        }
        if (!empty($user_info['account_id'])) {
            return $this->returnApi(202, "您已绑定其他读者证，无需重复绑定");
        }
        $union_id = UserAppletInfo::where('id', $user_info['applet_id'])->value('union_id');
        if (empty($union_id)) {
            return $this->returnApi(202, "信息获取失败");
        }

        $yzRecomObj = new YzRecomController();
        $yz_recom_info = $yzRecomObj->getReaderInfo($union_id);
        if ($yz_recom_info['code'] != 200) {
            return $this->returnApi(202, "查询失败");
        }
        $account = hide_by_percentage($yz_recom_info['content']['account']);
        return $this->returnApi(200, "系统检测到“YUE·渝中”已绑定读者证: " . $account . ' ;是否立即绑定！', true);
    }
    /**
     * 获取 YUE书馆 的读者信息 并绑定
     * @user_id 用户id    必须要微信授权
     */
    public function getLibReaderInfoAndBind()
    {
        $user_id = $this->request->user_info['id'];
        $user_info = UserInfo::where('id', $user_id)->first();
        if (empty($user_info['applet_id'])) {
            return $this->returnApi(202, "信息获取失败");
        }
        if (!empty($user_info['account_id'])) {
            return $this->returnApi(202, "您已绑定其他读者证，无需重复绑定");
        }
        $wechat_info = UserAppletInfo::where('id', $user_info['applet_id'])->first();
        if (empty($wechat_info)) {
            return $this->returnApi(202, "信息获取失败2");
        }

        $yzRecomObj = new YzRecomController();
        $yz_recom_info = $yzRecomObj->getReaderInfo($wechat_info['union_id']);
        if ($yz_recom_info['code'] != 200) {
            //修改截止时间
            return $this->returnApi(202, "绑定失败");
        }
        $userLibraryInfoModel = new UserLibraryInfo();
        //判断是否被其他读者证绑定
        $is_exixts_bind = $userLibraryInfoModel->isBindAccount($yz_recom_info['content']['account'], $user_id);
        if ($is_exixts_bind !== true) {
            return $this->returnApi(202, $is_exixts_bind);
        }

        //立即绑定在当前用户上
        $res = $userLibraryInfoModel->bindExistsReader($user_id, $yz_recom_info['content']);
        if ($res) {
            return $this->returnApi(200, "绑定成功", true, [
                'account' => $yz_recom_info['content']['account'],
                'username' => $yz_recom_info['content']['username']
            ]);
        } else {
            return $this->returnApi(202, "绑定失败");
        }
    }
}
